﻿using Esint.Common;
using Esint.JudicialAuction.Model;
using Esint.JudicialAuction.Model.Common;
using System;
using System.Collections.Generic;
using System.Web;
using System.Web.SessionState;
using System.Linq;
using Esint.Common.Web;

namespace WebJudicialAuction.admin.bases
{
    /// <summary>
    /// 暂时不用
    /// </summary>
    public abstract class BaseHandler : IRequiresSessionState
    {
        private bool isValidPower = false;

        /// <summary>
        /// 是否验证用户权限
        /// </summary>
        protected bool IsValidPower { get => isValidPower; set => isValidPower = value; }

        /// <summary>
        /// 权限根id
        /// </summary>
        protected string PowerRootId { get; set; }

        /// <summary>
        /// 当前登录用户
        /// </summary>
        protected Sys_UserInfo CurrentUser { get; set; }

        /// <summary>
        /// 当前登录的用户id
        /// </summary>
        protected string CurrentUserId
        {
            get { return this.CurrentUser == null ? "00000000-0000-0000-0000-000000000000" : CurrentUser.UserId; }
        }

        /// <summary>
        /// 用户是否登录标识
        /// </summary>
        private bool isUserLogin = false;

        /// <summary>
        /// 用户是否登录标识
        /// </summary>
        public bool IsUserLogin
        {
            get { return isUserLogin; }
            set { isUserLogin = value; }
        }
        
        private bool ignoreUserLogin = false;

        /// <summary>
        /// 是否忽略用户登录状态
        /// </summary>
        public bool IgnoreUserLogin
        {
            get { return ignoreUserLogin; }
            set { ignoreUserLogin = value; }
        }

        /// <summary>
        /// 请求上下文
        /// </summary>
        public HttpContext OwnContext { get; set; }
        
        /// <summary>
        /// 权限验证
        /// </summary>
        /// <param name="requestFunc"></param>
        /// <param name="areaCode"></param>
        protected virtual void PowerValid(string requestFunc, string areaCode = null)
        {
            if (CurrentUser != null)
            {
                var powerList = CurrentUser.UserPowerList;
                
                
                var rootObj = areaCode.IsNullOrEmpty() ? powerList.Find(x => x.MenuId == this.PowerRootId) : powerList.Find(x=>x.MenuId == this.PowerRootId && x.AreaCode == areaCode);
                if (rootObj != null)
                {
                    var userPowerIdList = (from t in powerList select t.MenuId).ToList();
                    var allMenus = this.OwnContext.Application["MenuList"] as List<Sys_MenuInfo>;
                    var qyAsyncFuncList = (from t in allMenus where t.RootId == this.PowerRootId && t.Level == 3 && userPowerIdList.Contains(t.MenuId) select t.MenuName);

                    if (qyAsyncFuncList.FirstOrDefault().IsNotNullOrEmpty())
                    {
                        var asyncFuncList = qyAsyncFuncList.ToList();
                        if (!asyncFuncList.Contains(requestFunc))
                        {
                            throw new PowerValidException(Validator.NotHasPower);
                        }
                    }
                    else
                    {
                        throw new PowerValidException(Validator.NotHasPower);
                    }
                }
                else
                {
                    throw new PowerValidException(Validator.NotHasPower);
                }
            }
        }

        /// <summary>
        /// 请求合法性验证
        /// </summary>
        protected virtual void RequestLegalValid(string requestFunc)
        {
            CurrentUser = null;
            if (OwnContext.Session[SessionKey.UserInfo] != null)
            {
                CurrentUser = OwnContext.Session[SessionKey.UserInfo] as Sys_UserInfo;
                IsUserLogin = true;
                if (isValidPower)
                {
                    PowerValid(requestFunc);
                }
            }
            else
            {
                IsUserLogin = false;
                if (!IgnoreUserLogin)
                {
                    var res_obj = new AjaxResult() { flag = AjaxResultFlag.NotLogin, msg = AjaxMessage.UserNotLogin };
                    OwnContext.Response.Write(CommonExtend.ConvertTJson(res_obj));
                    OwnContext.Response.End();
                }
            }
        }

        /// <summary>
        /// 调用对应子类的处理逻辑方法
        /// </summary>
        /// <param name="req_type">请求的分支方法</param>
        /// <param name="dicData">请求传送的数据</param>
        /// <param name="logModel">日志对象</param>
        /// <returns>AjaxResult对象作为处理结果</returns>
        protected abstract AjaxResult BusinessHandleFunc(string req_type, Dictionary<string, string> dicData);

        /// <summary>
        /// 总处理请求方法
        /// </summary>
        /// <param name="context"></param>
        public void ProcessRequest(HttpContext context)
        {
            string str_reqtype = !string.IsNullOrEmpty(context.Request["rtype"]) ? context.Request["rtype"] : string.Empty;

            AjaxResult res = null;
            OwnContext = context;

            context.Response.ContentType = "text/plain";
            
            try
            {
                RequestLegalValid(str_reqtype);

                #region 采集UI提交来的信息
                Dictionary<string, string> jsonData = new Dictionary<string, string>();

                foreach (var key in OwnContext.Request.Form.Keys)
                {
                    string currentValue = OwnContext.Request.Form[key.ToString()];
                    if (currentValue == "null")
                    {
                        currentValue = string.Empty;
                    }

                    if (currentValue != null)
                    {
                        currentValue = currentValue.Trim();
                    }

                    jsonData.Add(key.ToString().Trim(), currentValue);
                }
                #endregion

                //调用具体处理方法
                res = BusinessHandleFunc(str_reqtype, jsonData);
            }
            catch (PowerValidException powerEx)
            {
                res = new AjaxResult() { flag = AjaxResultFlag.ValidError, msg = powerEx.Message };
            }
            catch (DataValidException validEx)
            {
                res = new AjaxResult() { flag = AjaxResultFlag.ValidError, msg = validEx.Message };
            }
            catch (Exception ex)
            {
                CommonExtend.ErrorLog(ex, string.Empty);
                res = new AjaxResult();
                res.flag = AjaxResultFlag.ServerError;
                res.msg = AjaxMessage.ServerError;
            }

            string strres = CommonExtend.ConvertTJson(res);
            context.Response.Write(strres);
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
        
    }

}